package cn.dogger.easyboot.login.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dogger.easyboot.common.result.AjaxResult;
import cn.dogger.easyboot.login.service.LoginService;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;

/**
 * @author dogger
 * 2021/8/3 15:14
 */
@RestController
@RequestMapping("/login")
@Api(value = "登录类",tags = "登录类")
public class LoginController {

    private final LoginService service;

    public LoginController(LoginService service) {
        this.service = service;
    }

    @ApiOperation(value = "登录")
    @GetMapping("doLogin")
    public AjaxResult doLogin(@RequestBody LoginBO bo) {
        service.doLogin(bo.getUserName(),bo.getPassword(),bo.getVerificationCode());
        if("cb0496b9fd76d928".equals("")){
            StpUtil.login("");
            return AjaxResult.success("登录成功");
        }
        return AjaxResult.error("登录失败");
    }


    @ApiOperation(value = "查看登录状态")
    @GetMapping("isLogin")
    public AjaxResult isLogin() {
        return AjaxResult.success(StpUtil.isLogin());
    }


    @ApiOperation(value = "注销登录")
    @GetMapping("logout")
    public AjaxResult logout(){
      StpUtil.logout();
      return AjaxResult.success();
    }

    @ApiOperation(value = "验证码")
    @GetMapping("captcha")
    public AjaxResult captcha(HttpServletRequest request, HttpServletResponse response){
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 三个参数分别为宽、高、位数
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48,5);
        captcha.setLen(3);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text();  // 获取运算的结果：5
        // 验证码存入session
        request.getSession().setAttribute("captcha", captcha.text());
        // 输出图片流
        return AjaxResult.success("",captcha.toBase64());
    }
}

@Data
class LoginBO{
    /**
     * 用户名
     */
    String userName;

    /**
     * 密码
     */
    String password;

    /**
     * 验证码
     */
    String verificationCode;
}
